package com.java.filter;

import com.java.config.WhiteListConfig;
import com.java.service.AuthService;
import com.java.util.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
//@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private WhiteListConfig whiteListConfig;

    @Autowired
    private AuthService authService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().toString();

        log.info("请求路径：{}", uri);

        // 白名单放行
        for (String s : whiteListConfig.getWhiteList()) {
            if (uri.endsWith(s)) {
                log.info("白名单列表 {}", whiteListConfig.getWhiteList());
                return chain.filter(exchange);
            }
        }

        // 校验token是否携带
        List<String> list = request.getHeaders().get("token");
        String token = list != null ? list.get(0) : "";
        if (!StringUtils.hasText(token)) {
            log.info("401，token未携带");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 校验token是否有效
        ResultVo resultVo = authService.verify(token);
        if (resultVo.getCode() == HttpStatus.INTERNAL_SERVER_ERROR.value()){
            log.info("500，token校验失败");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        log.info("200，token校验通过");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }

}
